<template>
  <div class="common-container px_8">
    <el-breadcrumb separator="/" class="pt_8 pb_16">
      <el-breadcrumb-item @click="handleBack">数据集</el-breadcrumb-item>
      <el-breadcrumb-item>CSV</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :label-width="80" label-placement="left" :model="query" size="small">
      <el-form-item label="名称:" prop="name">
        <el-input placeholder="请输入CSV名称" v-model.trim="query.name" @keyup.enter.native="getMyCSVList" clearable @change="getMyCSVList" />
      </el-form-item>
      <el-form-item label="备注:" prop="remark">
        <el-input placeholder="请输入备注" v-model.trim="query.remark" @keyup.enter.native="getMyCSVList" clearable @change="getMyCSVList" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getMyCSVList">
          <el-icon style="vertical-align: middle;">
            <Search></Search>
          </el-icon>
          <span style="vertical-align: middle;">查询</span>
        </el-button>
        <el-button type="success" @click="handleModalAddAction">
          <el-icon style="vertical-align: middle;">
            <CirclePlus></CirclePlus>
          </el-icon>
          <span style="vertical-align: middle;">新增</span>
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="csvList" border class="w_100" v-loading="csvLoading">
      <el-table-column type="index" width="50" label="序号" align="center" />
      <el-table-column property="name" align="center" label="名称" />
      <el-table-column align="center" property="remark" label="备注" />
      <el-table-column align="center" property="create_timestamp" label="创建时间">
        <template #default="scope">
          <span>{{ formatTime(scope.row.create_timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" type="success" @click="handleModalEditAction(scope.row)">更新</el-button>
          <el-button size="small" type="danger" @click="handleModalDelAction(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="mt_16 right" v-model:currentPage="query.size" :page-size="query.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    <el-drawer v-model="CSVOpModel" :title="modalTitle[modalStatus]" size="28%" direction="rtl">
      <el-form :model="csvForm" :rules="rules" ref="csvFormRef" label-placement="left" :label-width="60" size="small">
        <el-form-item label="名称:" prop="name">
          <el-input placeholder="请输入名称" v-model.trim="csvForm.name" clearable />
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input placeholder="请输入备注" type="textarea" v-model.trim="csvForm.remark" />
        </el-form-item>
        <el-upload class="text_center" :action="requestUrl" :headers="{Authorization:token}" drag :multiple="false" :on-success="handleCSVUploadFinish"
          @before-upload="beforeCSVUpload">
          <el-icon class="el-icon--upload">
            <upload-filled />
          </el-icon>
          <div class="el-upload__text">
            拖拽到这上传 <em>点击上传</em>
          </div>
        </el-upload>
      </el-form>
      <div class="request-content">
        <div class="request-content_title">查询结果</div>
        <my-monaco-editor language="json" :code="requestData" :auto-format="true"></my-monaco-editor>
      </div>
      <div class="footer-modal fixed bottom_0 p_8 text_right right_0">
        <el-button @click="handleCloseModal" size="small" v-loading="formLoading" class="footer-modal--btn">取消
        </el-button>
        <el-button v-if="modalStatus ==='add'" type="primary" size="small" class="footer-modal--btn base-primary-btn m_lr_10" v-loading="formLoading"
          @click="handleAddCSV">确认
        </el-button>
        <el-button v-if="modalStatus ==='edit'" type="primary" size="small" v-loading="formLoading" class="footer-modal--btn base-primary-btn m_lr_10"
          @click="handleEditCSV">更新
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from "vue";
import {
  addDataCSV,
  delDataCSV,
  editDataCSV,
  getDataCSVList,
  csvExec,
} from "../../../service/data_csv";
import { useRouter } from "vue-router";
import { getToken } from "../../../utils/storage";
import { CirclePlus, Search, UploadFilled } from "@element-plus/icons-vue";
import { formatDate } from "../../../utils/utils";

export default defineComponent({
  name: "my-data-csv",
  components: {
    UploadFilled,
    CirclePlus,
    Search,
  },
  setup() {
    const router = useRouter();
    const csvLoading = ref(false);
    const formLoading = ref(false);
    const token = ref("");
    const total = ref(0);
    const csvList = ref([]);
    const CSVOpModel = ref(false);
    const modalStatus = ref("add");
    const requestData = ref("");
    const requestUrl = ref();
    const modalTitle = ref({
      add: "新增CSV",
      edit: "编辑CSV",
    });
    const query = ref({
      size: 1,
      limit: 10,
      name: "",
      remark: "",
    });
    const handleSizeChange = (pageSize) => {
      query.value.size = 1;
      query.value.limit = pageSize;
      getDataCSVList();
    };
    const handleCurrentChange = (size) => {
      query.value.size = size;
      getDataCSVList();
    };
    const csvForm = ref({
      name: undefined,
      remark: undefined,
      file: undefined,
    });
    const csvFormRef = ref(null);
    const resetForm = () => {
      csvForm.value = {
        name: undefined,
        remark: undefined,
        file: undefined,
      };
      requestData.value = "";
    };
    const handleModalAddAction = () => {
      resetForm();
      modalStatus.value = "add";
      CSVOpModel.value = true;
    };
    const handleCloseModal = () => {
      CSVOpModel.value = false;
    };
    const getMyCSVList = () => {
      csvLoading.value = true;
      getDataCSVList(query.value)
        .then((res) => {
          csvList.value = res.data.result;
          csvLoading.value = false;
          total.value = res.data.total;
        })
        .catch(() => {
          csvLoading.value = false;
        });
    };
    const handleTestCSV = () => {
      formLoading.value = true;
      csvFormRef.value.validate((errors) => {
        if (!errors) {
          csvExec(csvForm.value).then((res) => {
            formLoading.value = false;
            ElMessage({
              type: "success",
              message: "连接CSV成功",
            });
            requestData.value = JSON.stringify(res);
          });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleAddCSV = () => {
      formLoading.value = true;
      csvFormRef.value.validate((errors) => {
        if (!errors) {
          addDataCSV(csvForm.value).then(() => {
            formLoading.value = false;
            ElMessage({
              type: "success",
              message: "新增CSV成功",
            });
            handleCloseModal();
            getMyCSVList();
          });
        } else {
          ElMessage.error("新增CSV失败");
          formLoading.value = false;
        }
      });
    };
    const handleModalEditAction = (rowData) => {
      resetForm();
      csvForm.value = rowData;
      modalStatus.value = "edit";
      CSVOpModel.value = true;
    };
    const handleEditCSV = () => {
      formLoading.value = true;
      csvFormRef.value.validate((errors) => {
        if (!errors) {
          editDataCSV(csvForm.value).then(() => {
            formLoading.value = false;
            ElMessage({
              type: "success",
              message: "编辑CSV成功",
            });
            handleCloseModal();
            getMyCSVList();
          });
        } else {
          ElMessage.error("编辑CSV失败");
          formLoading.value = false;
        }
      });
    };
    const handleModalDelAction = (rowData) => {
      ElMessageBox.confirm(`你确定删除 ${rowData.name} 么？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        handleDelCSV(rowData);
      });
    };
    const handleDelCSV = (rowData) => {
      delDataCSV({ data_csv_id: rowData.data_csv_id })
        .then(() => {
          ElMessage({
            type: "success",
            message: "删除CSV成功",
          });
          getMyCSVList();
        })
        .catch((err) => {
          ElMessage.error("删除CSV失败");
        });
    };
    const handleBack = () => {
      router.push({ path: "index" });
    };
    const handleCSVUploadFinish = ({ file, event }) => {
      const res = JSON.parse(event.target.response);
      if (res.code === 0) {
        const { result, path } = res.data;
        csvForm.value.path = path;
        requestData.value = result;
      }
    };
    const beforeCSVUpload = ({ file, fileList }) => {
      if (fileList.length >= 1) {
        ElMessage.error("只能上传一个文件,如果已有上传文件,请删除!");
        return false;
      }
      if (file.file.type !== "application/vnd.ms-excel") {
        ElMessage.error("只能上传csv格式的文件，请重新上传");
        return false;
      }
      return true;
    };
    const formatTime = (num) => {
      return formatDate(num, "yyyy-MM-dd hh:mm:ss");
    };
    onMounted(() => {
      token.value = "Bearer " + getToken();
      requestUrl.value =
        import.meta.env.VITE_APP_REQUEST + "/v1/dataCSV/upload";
      getMyCSVList();
    });
    return {
      rules: {
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入CSV名称",
        },
        type: {
          required: true,
          message: "请选择CSV类型",
          trigger: ["change"],
        },
        server: {
          required: true,
          message: "请输入服务器地址",
          trigger: ["input", "blur"],
        },
      },
      token,
      query,
      total,
      csvLoading,
      formLoading,
      csvList,
      CSVOpModel,
      csvForm,
      csvFormRef,
      modalStatus,
      modalTitle,
      requestData,
      pagination,
      formatTime,
      handleSizeChange,
      handleCurrentChange,
      getMyCSVList,
      handleCloseModal,
      handleModalAddAction,
      resetForm,
      handleDelCSV,
      handleModalDelAction,
      handleModalEditAction,
      handleTestCSV,
      handleAddCSV,
      handleEditCSV,
      handleBack,
      requestUrl,
      handleCSVUploadFinish,
      beforeCSVUpload,
    };
  },
});
</script>

<style lang="less" scoped>
.request-content {
  .request-content_title {
    font-size: 14px;
    margin: 12px 0 12px;
    font-weight: bolder;
  }
}

.upload-csv {
  font-size: 44px;
}
</style>
